//
//  UTTaskCounterRecordViewController.swift
//  UniversalTool
//
//  Created by LGB on 2025/3/7.
//

import UIKit

class UTTaskCounterRecordViewController: UTBaseViewController {

    @IBOutlet weak var tableView: UITableView!
    
    lazy var datas: Array<UTTaskCounterItemModel> = {
        return Array<UTTaskCounterItemModel>()
    }()
    
    override func viewDidLoad() {
        super.viewDidLoad()
        self.view.backgroundColor = .clear
        self.tableView.delegate = self
        self.tableView.dataSource = self
        self.tableView.separatorStyle = .none
        self.tableView.register(UINib(nibName: "UTTaskCounterRecordCell", bundle: nil), forCellReuseIdentifier: "UTTaskCounterRecordCell")
        self.tableView.estimatedRowHeight = UITableView.automaticDimension
        self.tableView.rowHeight = UITableView.automaticDimension
        self.tableView.sectionHeaderHeight = CGFloat.zero
        self.tableView.sectionFooterHeight = CGFloat.zero
        if #available(iOS 15.0, *) {
            self.tableView.sectionHeaderTopPadding = 0.0
        }
        self.loadData()
    }
    
    fileprivate func loadData() {
        if let data = UTTaskCounterHelper.taskCounterInfo() {
            var list = Array<UTTaskCounterItemModel>()
            data.datas.forEach { item in
                if item.isFinish {
                    list.append(item)
                }
            }
            
            datas = list.reversed()
            self.tableView.reloadData()
        }
    }
    
    @IBAction func didClose(_ sender: UIButton) {
        self.dismiss(animated: false)
    }
    
}

extension UTTaskCounterRecordViewController: UITableViewDataSource, UITableViewDelegate {
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return datas.count
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        guard let cell = tableView.dequeueReusableCell(withIdentifier: "UTTaskCounterRecordCell") as? UTTaskCounterRecordCell else {
            fatalError("Unable to dequeue cell")
        }
        cell.selectionStyle = .none
        cell.model = datas[indexPath.row]
        return cell
    }
    
}

